"use strict";
var prefix = "/report/legalPerson";
var legalPersonId = $("#legalPersonId").val();
var companyName = $('#companyName').text();
$(function(){
	$("body").on("click",".basic-type-img",function(){
		$(this).parent().siblings(".detail-type").slideToggle();
		if($(this).hasClass("basic-type-img-bottom")){
			$(this).removeClass("basic-type-img-bottom");
			$(this).addClass("basic-type-img-top");
		}else if($(this).hasClass("basic-type-img-top")){
			$(this).removeClass("basic-type-img-top");
			$(this).addClass("basic-type-img-bottom");
		}
	})

	$("body").on("click",".detail-type-img",function(){
		$(this).parent().siblings("table").fadeToggle();
		if($(this).hasClass("detail-type-img-sub")){
			$(this).removeClass("detail-type-img-sub");
			$(this).addClass("detail-type-img-add");
		}else if($(this).hasClass("detail-type-img-add")){
			$(this).removeClass("detail-type-img-add");
			$(this).addClass("detail-type-img-sub");
		}
	})
	init(legalPersonId);
	loadGauge();
})

/**
 * 查询当前法人信用报告
 * @param legalPersonId
 * @returns
 */
function init(legalPersonId){
	$.ajax({
		data : {
			legalPersonId : legalPersonId
		}, 
		url : prefix + '/detail' ,
		success : function(r) {
			if (r.code != 0) {
				layer.msg(r.msg);
			}else{
				
				var countStr = "";
				var countData = r.obj.busList;
				$.each(countData,function(k1,v1){
					countStr += `<div class="total-box">
									<div id="busi-id-`+ v1.busiId +`" class="num">0</div>
									<div class="title">`+ v1.busiName +`</div>
								</div>`;
				})
				$("#count").html(countStr);
				
				var Str = "";
				var data = r.obj.detailMap;
				$.each(data,function(key1,value1){
					Str += `<div class="basic-type">
								<div class="basic-type-head clearfix">
									<h2>${key1}</h2>
									<div class="basic-type-img basic-type-img-bottom"></div>
								</div>`;
					$.each(value1,function (key2,value2){
						if(key2 == "工商信息"){	// 遍历工商信息
						Str += `<div class="detail-type">
									<div class="detail-type-head clearfix">
										<h3>${key2}</h3>
										<div class="detail-type-img detail-type-img-add"></div>
									</div>
									<table class="registration-message">`;
						var spStr = "";
							for(let i = 0;i<value2.length;i = i+2){
								if($("#busi-id-"+ value2.busi_id).length > 0){
									$("#busi-id-"+ value2.busi_id).html(value2.busi_value);
								}
								if(i == (value2.length-1) ){
								Str +=	`<tr>
											<td>${value2[i].busi_name}</td>
											<td colspan="3">${value2[i].busi_value}</td>
										</tr>`	
								}else if(value2[i].busi_name == "经营范围" || value2[i+1].busi_name == "经营范围"){
									spStr  += `<tr>
										<td>${value2[i].busi_name}</td>
										<td colspan="3">${value2[i].busi_value}</td>
									 </tr>
									 <tr>
										<td>${value2[i+1].busi_name}</td>
										<td colspan="3">${value2[i+1].busi_value}</td>
									 </tr>`
								}else{
								Str +=	`<tr>
											<td>${value2[i].busi_name}</td>
											<td>${value2[i].busi_value}</td>
											<td>${value2[i+1].busi_name}</td>
											<td>${value2[i+1].busi_value}</td>
										</tr>`
								}
							}
						Str += spStr;
						Str +=		`</table>
								</div>`;
						}else{	// 遍历其他信息
						Str += `<div class="detail-type">
									<div class="detail-type-head clearfix">
										<h3>${key2}</h3>
										<div class="detail-type-img detail-type-img-add"></div>
									</div>
									<table class="other-message">`;
							if(value2.length == 0){	// 判断是否存在记录
								Str +=	`<tr>
											<td colspan="2">无记录</td>
											</tr>`
							}else{
								$.each(value2,function(key3,value3){
									if($("#busi-id-"+ value3.busi_id).length > 0){
										$("#busi-id-"+ value3.busi_id).html(value3.busi_value);
									}
									switch(value3.link_way)
									{
									case 0:
										Str +=	`<tr>
													<td>${value3.busi_name}</td>
													<td><a href="javaScript:void(0)" onclick="queryDetail('${legalPersonId}','${value3.busi_id}',this)">${value3.busi_value}</a></td>
												</tr>`
									  break;
									case 1:
										Str +=	`<tr>
													<td>${value3.busi_name}</td>
													<td><a href="javaScript:void(0)" onclick="queryLegal('${legalPersonId}','${value3.busi_id}',this)">${value3.busi_value}</a></td>
												</tr>`
									  break;
									case 2:
										Str +=	`<tr>
													<td>${value3.busi_name}</td>
													<td><a href="javaScript:void(0)" onclick="queryNatural('${legalPersonId}','${value3.busi_id}',this)">${value3.busi_value}</a></td>
												</tr>`
										  break;
									case 3:
										Str +=	`<tr>
													<td>${value3.busi_name}</td>
													<td>${value3.busi_value}</td>
												</tr>`
										  break;
									case 4:
										Str +=	`<tr>
													<td>${value3.busi_name}</td>
													<td><a href="javaScript:void(0)" onclick="queryQiChacha('${companyName}','${value3.busi_id}',this)">查看详情</a></td>
												</tr>`
										  break;
									default:
										
									}
									
								})
							}
						Str +=		`</table>
								</div>`;
						}
					})			
								
					Str += `</div>`;
				})
				$("#msg").html(Str);
			}
		}
	})
}


/**
 * 查询明细
 * @param naturalPersonId	自然人ID
 * @param busiId	指标ID
 * @param _this	当前元素节点
 * @returns
 */
function queryDetail(legalPersonId,busiId,_this){
	if($(_this).parents("tr").next().find(".detail-message").length != 0){
		$(_this).parents("tr").next().fadeToggle();
	}else{
		$.ajax({
			data : {
				legalPersonId : legalPersonId,
				busiId : busiId
			}, 
			url : prefix + '/linkReport' ,
			success : function(r) {
				if(r.th.length <=0){
					window.open("/report/legalPerson/viewDetail/" + r.tr[0].legal_person_id)
				}else{
					var Str = `	<td colspan="2">
									<div>
										<table class="detail-message">
											<tbody>
												<tr>`
						$.each(r.th,function(key1,value1){
							Str += `				<th>${value1}</th>`
						})
							Str +=				`</tr>`
						$.each(r.tr,function(key2,value2){
							Str +=				`<tr>`
							$.each(value2,function(key3,value3){
									Str +=			`<td>${value3}</td>`
							})
							Str +=				`</tr>`
						})
						Str +=				`</tbody>
										</table>
									</div>
								</td>
							</tr>`;
					$(_this).parents("tr").after(Str)
				}
			}
		})
	}
}

/**
 * 企查查接口
 * @param companyName 企业名称
 * @param busiId 指标ID
 * @param _this 当前元素节点
 * @returns
 */
function queryQiChacha(companyName,busiId,_this){
	if($(_this).parents("tr").next().find("#qichacha-message").length != 0){
		$(_this).parents("tr").next().fadeToggle();
	}else{
		$.ajax({
			url: prefix + "/queryQiChacha",
			data: {
				companyName : companyName,
				busiId : busiId
			},
			success: function(r){
				var result = r.result;
				var Str  = "<tr>\n\r";
				  	  Str += "	<td id=\"qichacha-message\" colspan=\"2\">\n\r";
				  	  Str += "<div>";
				if(result != null){
					var key2Text =new Object; // 中文名对应
					for(var i in r.name){
						key2Text[i] = r.name[i];
					}
					var a = fixResult2(result,key2Text,"");
						  Str += a;
				}else{
					Str += "暂无数据!";
				}
				  Str += "</div>";
				  Str += "	</td>\n\r";
				  Str += "</tr>\n\r";
				  $(_this).parents("tr").after(Str);
			}
		})
	}
}

/**
 * 递归处理企查查数据
 * @param data 原始数据
 * @param key2Text 键名对应
 * @param _Str 拼接文本
 * @returns
 */
function fixResult2(data, key2Text, _Str) {
	var Str = _Str;
	if ($.isArray(data)) { // 如果传入对象是Array，则进行递归
		$.each(data, function(k, v) {
			Str = fixResult2(v, key2Text, Str);
		})
	} else if ($.isPlainObject(data)) { // 如果是Object，则进行遍历
		Str += "<table class=\"pub-table detail-message\">";
		$.each(data, function(k, v) {
			if ($.isPlainObject(v)) { // 如果是Object，则递归遍历
				if(key2Text[k] != undefined){
					Str += "<tr><th>" + key2Text[k] + "</th><td>";
					Str = fixResult2(v, key2Text, Str);
					Str += "</td></tr>";
				}
			} else if ($.isArray(v)) { // 如果是Array,则进行递归
				$.each(v, function(k2, v2) {
					Str = fixResult2(v2, key2Text, Str);
				})
			} else {
				if(key2Text[k] != undefined){
					Str += "<tr><th>" + key2Text[k] + "</th><td>" + v
							+ "</td></tr>"
				}
			}
		})
		Str += "</table>";
	}
	return Str;
}

/**
 * 查询法人信用报告
 * @param naturalPersonId	自然人ID
 * @param busiId	指标ID
 * @param _this	当前元素节点
 * @returns
 */
function queryLegal(legalPersonId,busiId,_this){
	if($(_this).parents("tr").next().find(".detail-message").length != 0){
		$(_this).parents("tr").next().fadeToggle();
	}else{
		$.ajax({
			data : {
				legalPersonId : legalPersonId,
				busiId : busiId
			}, 
			url : '/report/legalPerson/linkReport' ,
			success : function(r) {
				if(r.th.length <=0){
					window.open("/report/legalPerson/viewDetail/" + r.tr[0].legal_person_id)
				}else{
					var Str = `	<td colspan="2">
									<div>
										<table class="detail-message">
											<tbody>
												<tr>`
						$.each(r.th,function(key1,value1){
							Str += `				<th>${value1}</th>`
						})
							Str +=				`</tr>`
						$.each(r.tr,function(key2,value2){
							Str +=				`<tr class="cursor" onclick="javaScript:window.open('/report/legalPerson/viewDetail/${value2.legal_person_id}')">`
							$.each(value2,function(key3,value3){
								if(key3 != "legal_person_id"){
									Str +=			`<td>${value3}</td>`
								}
							})
							Str +=				`</tr>`
						})
						Str +=				`</tbody>
										</table>
									</div>
								</td>
							</tr>`;
					$(_this).parents("tr").after(Str)
				}
			}
		})
	}
}

/**
 * 查询自然人信用报告
 * @param naturalPersonId	自然人ID
 * @param busiId	指标ID
 * @param _this	当前元素节点
 * @returns
 */
function queryNatural(naturalPersonId,busiId,_this){
	if($(_this).parents("tr").next().find(".detail-message").length != 0){
		$(_this).parents("tr").next().fadeToggle();
	}else{
		$.ajax({
			data : {
				naturalPersonId : naturalPersonId,
				busiId : busiId
			}, 
			url : '/report/naturalPerson/linkReport' ,
			success : function(r) {
				if(r.th.length <=0){
					window.open("/report/naturalPerson/viewDetail/" + r.tr[0].natural_person_id)
				}else{
					var Str = `	<td colspan="2">
									<div>
										<table class="detail-message">
											<tbody>
												<tr>`
						$.each(r.th,function(key1,value1){
							Str += `				<th>${value1}</th>`
						})
							Str +=				`</tr>`
						$.each(r.tr,function(key2,value2){
							Str +=				`<tr class="cursor" onclick="javaScript:window.open('/report/naturalPerson/viewDetail/${value2.natural_person_id}')">`
							$.each(value2,function(key3,value3){
								if(key3 != "natural_person_id"){
									Str +=			`<td>${value3}</td>`
								}
							})
							Str +=				`</tr>`
						})
						Str +=				`</tbody>
										</table>
									</div>
								</td>
							</tr>`;
					$(_this).parents("tr").after(Str)
				}
			}
		})
	}
}



/**
 * 跳转到打印报告预览页
 * @returns
 */
function printReport(){
	window.open(prefix+"/printReport/"+legalPersonId+"/"+$("#timestamp").text());
}

/*QRCode();

*//**
 * 获取二维码
 * @returns
 *//*
function QRCode(){
			var r = `{"timeStamp":"`+ $("#timestamp").text() +`","companyName":"`+ $("#companyName").text() +`"}`;
			 var str = JSON.stringify(r)
			 $('#QRCode').qrcode({
		          render:"canvas",
		          height:120,
		          width:120,
		          correctLevel:0,
		          text:toUtf8(str)
		      }); 
			 QRCode = toUtf8(str);
}
*/
/**
 * 转换成UTF-8字符集，避免乱码
 * @param str
 * @returns
 */
function toUtf8(str) {
    var out, i, len, c;
    out = "";
    len = str.length;
    for (i = 0; i < len; i++) {
        c = str.charCodeAt(i);
        if ((c >= 0x0001) && (c <= 0x007F)) {
            out += str.charAt(i);
        } else if (c > 0x07FF) {
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
            out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        } else {
            out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        }
    }
    return out;
}


function loadGauge() {
	
	$.ajax({
		cache : true,
		type : "POST",
		url : "/ce/score/scoreViewDefault",
		data: {
				name:$('#companyName').text()
			  }, // 请求数据的ajax的data属性
		async : false,
		error : function(request) {
			parent.layer.alert("网络超时");
		},
		success : function(obj) {
			$("#levelDesc").text(obj.levelDesc);
			$("#levelName").text(obj.levelName);
			var gaugeChart = echarts.init(document.getElementById("echarts-gauge-chart"));
			var option = {
				    tooltip : {
				        formatter: "{a} <br/>{b} : {c}"
				    },
				    
				    series : [
			            {
			                name:'信用分',
			                type:'gauge',
			                radius : '90%',
			                min:0,
			                max:Number(obj.scoreTotal),
			                splitNumber:10,
			                axisLine: {            // 坐标轴线
			                    lineStyle: {       // 属性lineStyle控制线条样式
			                        width: 10
			                    }
			                },
			                axisTick: {            // 坐标轴小标记
			                    length :15,        // 属性length控制线长
			                    lineStyle: {       // 属性lineStyle控制线条样式
			                        color: 'auto'
			                    }
			                },
			                splitLine: {           // 分隔线
			                    length :14,         // 属性length控制线长
			                    lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
			                        color: 'auto'
			                    }
			                },
			                title : {
			                    textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
			                        fontWeight: 'bolder',
			                        fontSize: 14,
			                        fontStyle: 'italic'
			                    }
			                },
			                detail : {
			                    textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
			                        fontWeight: 'bolder'
			                      
			                    }
			                }
			                ,
			                data:[{value: Number(obj.score), name: obj.levelName}]
			            }
				    ]
				};

			gaugeChart.setOption(option);
			$(window).resize(gaugeChart.resize);
			
//			if (data.code == 0) {
//				parent.layer.msg("操作成功");
//				parent.reLoad();
//				var index = parent.layer.getFrameIndex(window.name);
//				parent.layer.close(index);
//
//			} else {
//				parent.layer.alert(data.msg)
//			}

		}
	});

};

